import * as api from '../../api/common';

Page({
  data: {
    showVerification: false,
    phoneNumber: '',
    verificationCode: '',
    password: '',
    countdown: 0,
    timer: null,
    checked: false,
    loading: false
  },

  onLoad(options) {
    // 页面加载时的初始化工作，如果有需要可以在这里处理
  },

  onUnload() {
    // 页面卸载时清除定时器，避免内存泄漏
    if (this.data.timer) {
      clearInterval(this.data.timer);
    }
  },

  // 去登录页面
  loginByAccount() {
    tt.redirectTo({
      url: '../loginByAccount/index'
    });
  },

  // 同意/取消用户协议
  toggleCheckbox() {
    this.setData({
      checked: !this.data.checked
    });
  },

  // 输入手机号
  inputPhone(e) {
    this.setData({
      phoneNumber: e.detail.value
    });
  },

  // 输入验证码
  inputVerificationCode(e) {
    this.setData({
      verificationCode: e.detail.value
    });
  },

  // 输入密码
  inputPassword(e) {
    this.setData({
      password: e.detail.value
    });
  },

  // 校验手机号格式
  checkPhoneNumber(phoneNumber) {
    const reg = /^1\d{10}$/;
    return reg.test(phoneNumber);
  },

  // 发送验证码
  async sendVerificationCode() {
    if (this.data.loading) {
      return
    }
    this.setData({
      loading: true
    })
    const phoneNumber = this.data.phoneNumber.trim();

    if (!this.checkPhoneNumber(phoneNumber)) {
      tt.showToast({
        title: '请输入正确的手机号码',
        icon: 'none'
      });
      this.setData({
        loading: false
      })
      return;
    }

    try {
      const response = await api.sendVerificationCode({
        phone: phoneNumber
      });
      tt.showToast({
        title: '验证码发送成功',
        icon: 'success'
      });
      if (response.code == 0) {
        tt.showToast({
          title: response.msg,
          icon: 'none'
        });
      } else {
        this.setData({
          showVerification: true
        });
        this.startCountdown();
      }
    } catch (error) {
      tt.showToast({
        title: error,
        icon: 'none'
      });
    } finally {
      this.setData({
        loading: false
      })
    }
  },

  // 开始倒计时
  startCountdown() {
    let count = 60;
    this.setData({
      countdown: count
    });
    this.data.timer = setInterval(() => {
      count--;
      if (count >= 0) {
        this.setData({
          countdown: count
        });
      } else {
        clearInterval(this.data.timer);
        this.setData({
          countdown: 0
        });
      }
    }, 1000);
  },

  // 勾选
  toggleCheckbox() {
    this.setData({
      checked: !this.data.checked // 切换勾选状态
    });
  },
  gotoPrivacyPage() {
    tt.navigateTo({
      url: 'pages/privacy/index'
    });
  },

  gotoServicePage() {
    tt.navigateTo({
      url: 'pages/service/index'
    });
  },
  // 注册按钮点击事件
  async register() {
    if (this.data.loading) {
      return
    }
    this.setData({
      loading: true
    })

    const phoneNumber = this.data.phoneNumber.trim();
    const verificationCode = this.data.verificationCode.trim();
    const password = this.data.password.trim();

    if (!this.checkPhoneNumber(phoneNumber)) {
      tt.showToast({
        title: '请输入正确的手机号码',
        icon: 'none'
      });
      this.setData({
        loading: false
      })
      return;
    }

    if (!verificationCode) {
      tt.showToast({
        title: '请输入验证码',
        icon: 'none'
      });
      this.setData({
        loading: false
      })
      return;
    }

    if (!password) {
      tt.showToast({
        title: '请输入密码',
        icon: 'none'
      });
      this.setData({
        loading: false
      })
      return;
    }

    if (!this.data.checked) {
      tt.showToast({
        title: '请阅读并同意用户协议和隐私权条款',
        icon: 'none'
      });
      this.setData({
        loading: false
      })
      return;
    }

    try {
      const ttLoginRes = await new Promise((resolve, reject) => {
        tt.login({
          success: (res) => resolve(res),
          fail: (err) => reject(err)
        });
      });

      if (!ttLoginRes.code) {
        throw new Error('登录失败，未获取到 code');
      }

      const tt_code = ttLoginRes.code;
      const openidResponse = await api.getOpenid({
        code: tt_code
      });

      if (!openidResponse.data || !openidResponse.data.openid) {
        tt.showToast({
          title: '获取 openid 失败',
          icon: 'none'
        });
        return;
      }

      const openid = openidResponse.data.openid;

      const response = await api.register({
        code: verificationCode,
        phone: phoneNumber,
        password: password,
        openid: openid
      });

      if (response.code === 0) {
        tt.showToast({
          title: response.msg,
          icon: 'none'
        });
      } else {
        tt.showToast({
          title: '注册成功',
          icon: 'success'
        });
        // 登录成功处理
        tt.setStorageSync('info', response.data);
        // 跳转首页
        tt.redirectTo({
          url: '../index/index'
        });
        // tt.navigateTo({
        //   url: '../loginByAccount/index'
        // });
      }
    } catch (error) {
      tt.showToast({
        title: error,
        icon: 'none'
      });
    } finally {
      setTimeout(() => {
        this.setData({
          loading: false
        })
      }, 1000)
    }
  }

});